package com.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    public static String doGet(String url, Map<String, Object> param) {
        return doGet(url, null, param);
    }

    /**
     * 发送Get请求，包含参数
     *
     * @param url
     * @param param 可以为空
     * @return
     */
    public static String doGet(String url, Map<String, Object> header, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000) //连接超时时间
                .setConnectionRequestTimeout(60000) //从连接池中取的连接的最长时间
                .setSocketTimeout(60 * 1000) //数据传输的超时时间
                .build();
        //设置请求配置时间
        String resultString = "";
        HttpGet httpGet = null;
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);

            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key).toString());
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            httpGet = new HttpGet(uri);
            httpGet.setConfig(config);
            if (null != header) {
                for (Map.Entry<String, Object> entry : header.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue().toString());
                }
            }
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (null != httpGet) {
                    httpGet.releaseConnection();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }


    public static String doGet(String url) {
        return doGet(url, null, null);
    }

    public static String doPost(String url, Map<String, Object> param) {
        return doPost(url, null, param);
    }

    /**
     * 发送POST请求，参数以MAP形式传递
     *
     * @param url
     * @param param
     * @return
     */
    public static String doPost(String url, Map<String, Object> header, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000) //连接超时时间
                .setConnectionRequestTimeout(60000) //从连接池中取的连接的最长时间
                .setSocketTimeout(60 * 1000) //数据传输的超时时间
                .build();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(config);
            if (null != header) {
                for (Map.Entry<String, Object> entry : header.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue().toString());
                }
            }
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key).toString()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /**
     * 发送POST请求，不带参数
     *
     * @param url
     * @return
     */
    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) throws RuntimeException {
        return doPostJson(url, null, json);
    }

    /**
     * 发送POST请求，参数以JSON形式传递
     *
     * @param url
     * @param json
     * @return
     */
    public static String doPostJson(String url, Map<String, Object> header, String json) throws RuntimeException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            if (null != header) {
                for (Map.Entry<String, Object> entry : header.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue().toString());
                }
            }

            HttpEntity entity = ("".equals(json)) ? new StringEntity(json, ContentType.APPLICATION_FORM_URLENCODED) : new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);

            URI uri = new URL(url).toURI();
            if ("https".equals(uri.getScheme())) {
                entity = HttpClientUtil.createSSLClient(httpPost);
            } else {
                httpClient = HttpClients.createDefault();
                response = httpClient.execute(httpPost);// 执行http请求
                entity = response.getEntity();
            }

            if (entity != null) {
                resultString = EntityUtils.toString(entity, "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("调用错误，原因：" + e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                    httpClient.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static HttpEntity createSSLClient(HttpPost httpPost) throws GeneralSecurityException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpEntity entity = null;
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]
                {tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", ssf, 443));
        try {
            HttpResponse response = httpClient.execute(httpPost);
            entity = response.getEntity(); // 获取响应实体
        } catch (IOException e) {
            throw new GeneralSecurityException("找不到服务器！");
        }
        return entity;
    }

    public static String doGDTGet(String urlStr, Map params) {
        String result = "";
        try {
            String urlString = urlStr
                    + "?level=" + params.get("level")
                    + "&group_by=" + params.get("groupBy")
                    + "&fields=" + params.get("fields")
                    + "&access_token=" + params.get("accessToken")
                    + "&account_id=" + params.get("accountId")
                    + "&date_range=" + params.get("dateRangeJson")
                    + "&timestamp=" + params.get("timestamp")
                    + "&nonce=" + params.get("nonce")
                    + "&page_size=" + params.get("page_size");


            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            result = response.toString();
            conn.disconnect();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


}
